/******************************************************************************
 * This program is a 100% Java Email Server.
 ******************************************************************************
 * Copyright (c) 2001-2011, Eric Daugherty (http://www.ericdaugherty.com)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of the copyright holder nor the
 *     names of its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 ******************************************************************************
 * For current versions and more information, please visit:
 * http://javaemailserver.sf.net/
 *
 * or contact the authors at:
 * java@ericdaugherty.com
 * andreaskyrmegalos@hotmail.com
 *
 ******************************************************************************
 * This program is based on the CSRMail project written by Calvin Smith.
 * http://crsemail.sourceforge.net/
 ******************************************************************************
 *
 * $Rev$
 * $Date$
 *
 ******************************************************************************/

package com.ericdaugherty.mail;

//Java Imports
import java.io.*;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.*;
import java.security.interfaces.RSAPrivateCrtKey;

/**
 *
 * @author Andreas Kyrmegalos
 */
public class Tools {

   static void createMD5File(String input) throws IOException, GeneralSecurityException{

      File output = new File(input+".md5");
      if (!output.exists()) output.createNewFile();
      FileOutputStream fos = new FileOutputStream(output);
      try {
         fos.write(Utils.getDerivedMD5(new File(input)));
         fos.write(System.getProperty("line.separator").getBytes());
      }
      finally {
         fos.flush();
         try {
            fos.close();
         }
         catch (IOException ioe) {}
      }
   }

   private static void createTruststoreWithCACertificate(String certificatePathname, String alias, String truststorePathname) {
      CertificateFactory cf = null;
      BufferedInputStream bis = null;
      FileOutputStream fos = null;
      Certificate serverCert = null;
      try {
         cf = CertificateFactory.getInstance("X.509");
         bis = new BufferedInputStream(new FileInputStream(new File(certificatePathname)));
         fos = new FileOutputStream(new File(truststorePathname));
         serverCert = (X509Certificate)cf.generateCertificate(bis);
         KeyStore ks = KeyStore.getInstance("jks");
         ks.load(null, null);
         ks.setCertificateEntry(alias, serverCert);
         ks.store(fos, "password".toCharArray());

      }
      catch (Exception e) {e.printStackTrace();}
      finally {
         if (bis!=null) {
            try {
               bis.close();
            }
            catch (IOException e) {}
         }
         if (fos!=null) {
            try {
               fos.close();
            }
            catch (IOException e) {}
         }
      }
   }

   private static void createKeystoreWithPrivateKey(String pkcs12Alias, String pkcs12Password, String pkcs12Pathname, String alias, String password, String keystorePathname ) {

      char[] pass = password.toCharArray();
      char[] pkcs12Pass = pkcs12Password.toCharArray();
      FileOutputStream fos = null;
      try {
         KeyStore tempks = KeyStore.getInstance("pkcs12", "SunJSSE");
         File pkcs12 = new File(pkcs12Pathname);
         tempks.load(new FileInputStream(pkcs12), pkcs12Pass);
         Key key = tempks.getKey(pkcs12Alias, pkcs12Pass);
         if (key == null) {
            throw new RuntimeException("Got null key from keystore!");
         }
         RSAPrivateCrtKey privKey = (RSAPrivateCrtKey) key;
         Certificate[] clientCerts = tempks.getCertificateChain(pkcs12Alias);
         if (clientCerts == null) {
            throw new RuntimeException("Got null cert chain from keystore!");
         }
         KeyStore.PrivateKeyEntry pke = new KeyStore.PrivateKeyEntry(privKey, clientCerts);
         KeyStore.ProtectionParameter kspp = new KeyStore.PasswordProtection(pass);
         fos = new FileOutputStream(keystorePathname);
         KeyStore ks = KeyStore.getInstance("jceks");
         ks.load(null, pass);
         ks.setEntry(alias, pke, kspp);
         ks.store(fos, pass);

      }
      catch (Exception e) {e.printStackTrace();}
      finally {
         for (int i=0;i<pass.length;i++) {
            pass[i] = 0x00;
         }
         if (fos!=null) {
            try {
               fos.close();
            } catch (IOException e) {}
         }
      }
   }

   public static void main(String[] input) throws IOException, GeneralSecurityException{

      if (input[0].toLowerCase().equals("md5")) createMD5File(input[1]);
      else if (input[0].toLowerCase().equals("tru")) createTruststoreWithCACertificate(input[1], input[2], input[3]);
      else if (input[0].toLowerCase().equals("key")) createKeystoreWithPrivateKey(input[1], input[2], input[3], input[4], input[5], input[6]);
   }

}
